/**
 * 
 */
package vn.smartware.co.framework.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * EncodingFilter
 * 
 * @author thuctt
 */
public class EncodingFilter implements Filter {

	private static Log log = LogFactory.getLog(EncodingFilter.class);
	
	private FilterConfig filterConfig = null;

	/**
	 * initialize
	 * 
	 * @param filterConfig
	 */
	public void init(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	/**
	 * do filter
	 * @param request 
	 * @param response 
	 * @param chain 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		if (request instanceof HttpServletRequest) {

			HttpServletRequest r = (HttpServletRequest) request;

			String encoding = filterConfig.getInitParameter("encoding");
			r.setCharacterEncoding(encoding);
			
			log.debug("Encoding doFilter " + encoding);
		}

		// pass the request on
		chain.doFilter(request, response);
	}

	/**
	 * dispose
	 */
	public void destroy() {
		this.filterConfig = null;
	}
}
